from django.contrib.auth.hashers import make_password, check_password
from rest_framework import status
from rest_framework.generics import CreateAPIView, RetrieveAPIView, ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import User
from .serializers import UserModelSerializer, MyTokenObtainPairSerializer, UserSetSerializer, UserUploadSerializers
from rest_framework_simplejwt.views import TokenObtainPairView
from .utils import save_user


class MyTokenObtainPairView(TokenObtainPairView):
    """
    用户登录视图
    """
    serializer_class = MyTokenObtainPairSerializer


class UserAPIView(CreateAPIView):
    """
    用户注册视图
    """
    queryset = User.objects.all()
    serializer_class = UserModelSerializer


class ChangePasswordAPIView(APIView):
    """
    修改密码视图
    """

    def post(self, request):
        pwd1 = request.data.get('origin_pwd')
        pwd2 = request.data.get('new_pwd')
        uid = request.data.get('uid')

        user = User.objects.get(id=uid)
        users = UserSetSerializer()
        if check_password(pwd1, user.serializable_value('password')):
            users.update(instance=user, validated_data={'password': make_password(pwd2)})
            return Response({'msg': '修改成功'}, status=status.HTTP_200_OK)
        else:
            return Response({'msg': '修改失败，参数错误'}, status=status.HTTP_404_NOT_FOUND)


class UserRetrieveAPIView(RetrieveAPIView):
    """
    用户信息视图
    """
    queryset = User.objects.filter()
    serializer_class = UserSetSerializer


class ChangeInfoAPIView(APIView):
    """
    修改用户信息视图
    """

    def post(self, request):
        data = request.data.get('info')
        uid = request.data.get('uid')
        user = User.objects.get(id=uid)

        flag = request.data.get('flag')
        data = save_user(flag, data)
        users = UserSetSerializer()
        users.update(instance=user, validated_data=data)
        return Response({'msg': 'ok'})


class UserUploadAPIView(APIView):
    """
    用户头像上传视图
    """

    def post(self, request):
        file_serializer = UserUploadSerializers(data=request.data)
        user = User.objects.get(id=request.data['uploader'])
        if file_serializer.is_valid():
            file_serializer.update(instance=user, validated_data={
                'id': request.data['uploader'],
                'avatar': request.data['file']
            })
            return Response({'msg': '上传成功'}, status=status.HTTP_200_OK)
        else:
            return Response({'msg': '上传失败'}, status=status.HTTP_404_NOT_FOUND)


class UserUploadListAPIView(ListAPIView):
    """
    用户头像获取视图
    """

    def get_queryset(self):
        fd = self.request.GET.dict()["uid"]
        queryset = User.objects.filter(id=fd)
        return queryset

    serializer_class = UserUploadSerializers
